# -*- coding: utf-8 -*-
# @Time    : 2024/11/10 13:55
# @Author  : CHNJX
# @File    : __init__.py.py
# @Desc    :

from flask import Blueprint, jsonify
from .device import device_bp
from .module import module_bp
from .coordinate import coordinate_bp
from .base_steps import base_step_bp
from .testcase import test_case_bp
from .test_suite import test_suite_bp
from .test_strategy import test_strategy_bp
from .data import data_bp
from .test_management import test_management_bp
from .mqtt import mqtt_bp
from .log_analysis import log_analysis_bp
from app.utils.response_handler import error_response
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.exceptions import HTTPException


# 创建主蓝图
bp = Blueprint('api', __name__)

# 注册所有子蓝图
bp.register_blueprint(device_bp, url_prefix='/devices')
bp.register_blueprint(module_bp, url_prefix='/module')
bp.register_blueprint(coordinate_bp, url_prefix='/coordinates')
bp.register_blueprint(base_step_bp, url_prefix='/steps')
bp.register_blueprint(test_case_bp, url_prefix='/test-cases')
bp.register_blueprint(test_suite_bp, url_prefix='/test-suites')
bp.register_blueprint(test_strategy_bp, url_prefix='/test_strategy')
bp.register_blueprint(data_bp, url_prefix='/data')
bp.register_blueprint(test_management_bp, url_prefix='/test-management')
bp.register_blueprint(mqtt_bp, url_prefix='/mqtt')
bp.register_blueprint(log_analysis_bp, url_prefix='/log-analysis')

# 全局错误处理
@bp.app_errorhandler(HTTPException)
def handle_http_error(error):
    """处理 HTTP 错误"""
    response = error_response(
        message=error.description,
        code=error.code
    )
    return jsonify(response), error.code

@bp.app_errorhandler(SQLAlchemyError)
def handle_db_error(error):
    """处理数据库错误"""
    response = error_response(
        message="数据库操作失败",
        code=500,
        data=str(error)
    )
    return jsonify(response), 500

@bp.app_errorhandler(Exception)
def handle_error(error):
    """处理其他所有错误"""
    response = error_response(
        message="服务器内部错误",
        code=500,
        data=str(error)
    )
    return jsonify(response), 500

# 健康检查路由
@bp.route('/health', methods=['GET'])
def health_check():
    """健康检查端点"""
    return jsonify({
        'code': 200,
        'message': 'success',
        'data': {
            'status': 'healthy',
            'version': '1.0.0'  # 你可以从配置中读取版本号
        }
    })

# API 信息路由
@bp.route('/', methods=['GET'])
def api_info():
    """API 信息端点"""
    return jsonify({
        'code': 200,
        'message': 'success',
        'data': {
            'name': 'Auto Test Platform API',
            'version': '1.0.0',
            'description': '自动化测试平台 API',
            'endpoints': [
                {'path': '/devices', 'description': '设备管理'},
                {'path': '/modules', 'description': '功能模块管理'},
                {'path': '/coordinates', 'description': '控件坐标管理'},
                {'path': '/steps', 'description': '基础步骤管理'},
                {'path': '/test-cases', 'description': '测试用例管理'},
                {'path': '/test-suites', 'description': '测试集合管理'},
                {'path': '/mqtt', 'description': 'MQTT配置和远程升级管理'},
                {'path': '/log-analysis', 'description': '日志分析服务：上传、分析、下载、删除日志文件'}
            ]
        }
    })
